﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Security.Cryptography;
using RestSharp;
using Newtonsoft.Json;
using System.Text;
using Newtonsoft.Json.Linq;
using System.Windows;
using CefSharp;

public class RestUtils
{
    private RestClient client;
    private string url;
    public string publickkey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtFHvmu+Xa6QmYCTLYKaD5yhwXAkECxurB2X9JVxr9K00mArcUwlM74mx8pFscOxKBvMLVxp8hJZZxAiLrNXi3BFto5XNlUpWxKSrHKeXw+RLXjoeOvIhvSusMV2hKpsEhJzBP47PSLBz5cy1+ndhEHhFAXJZt13yQkXM9jqg3uKdD5Dhrx73RuUJI+oUgRtvdaDwIryMm8rX16csRQgmOrbV64cwC56JCwyGtGknDIKMetdeJuVxHX2mWURV4AS+Nl5698Ls0fzOoWGbDQRyz+hDk3TF9UwTcoAKdU/rzFkSaBxgJ/29eUAtKlLzxH20RDVWU3DD3IBv/4+enMYpJQIDAQAB";
    public RestUtils()
    {
        url = "http://" + AppStatic.Server + ":" + AppStatic.Port;
        client = new RestClient(url);
        client.CookieContainer = new System.Net.CookieContainer();
    }
    
    public byte[] getCaptcha(string uuid)
    {
        var request = new RestRequest("/captcha.jpg?uuid=" + uuid, Method.GET, RestSharp.DataFormat.None);
        IRestResponse response = client.Execute(request);
        return response.RawBytes;
    }

    public Stream initImage()
    {
        var stream = new MemoryStream();
        try
        {
            var request = new RestRequest("/uploadfile/infoImage", Method.GET);
            IRestResponse response = client.Execute(request);
            if(response.StatusCode==System.Net.HttpStatusCode.OK)
            {
                var bts = response.RawBytes;
                stream.Write(bts, 0, bts.Length);
            }
            else
            {
                throw new Exception("网络请求错误");
            }
        }
        catch (Exception ex)
        {
            var byts = File.ReadAllBytes(Environment.CurrentDirectory + "/" + AppStatic.ImageUri);
            stream.Write(byts, 0, byts.Length);
        }
        stream.Seek(0, System.IO.SeekOrigin.Begin);
        return stream;
    }

    public bool login(string userName,string password)
    {
        var request = new RestRequest("/sys/login", Method.POST, RestSharp.DataFormat.Json);
        var contenType = "application/json";
        request.AddHeader("Accept", contenType);
        RSACryptoServiceProvider rsa = CreateRsaProviderFromPublicKey(publickkey);
        var logininfo = new loginInfo()
        {
            username = userName,
            password = password,
            mac = AppStatic.deviceCode
        };
        string jsonStr=JsonConvert.SerializeObject(logininfo);
        //string enryData = Convert.ToBase64String(rsa.Encrypt(Encoding.UTF8.GetBytes(jsonStr), false));
        //JObject sendData = new JObject();
        //sendData.Add("data", jsonStr);
        request.AddParameter(contenType, jsonStr, ParameterType.RequestBody);
        var response = client.Execute(request);
        if (response.StatusCode == System.Net.HttpStatusCode.OK)
        {
            JObject obj = (JObject)JsonConvert.DeserializeObject(response.Content);
             int status= obj.Value<int>("code");
            if (status != 500)
            {
                string token=obj.Value<string>("token");
                client.CookieContainer.Add(new System.Net.Cookie()
                {
                    Domain = AppStatic.Server,
                    Name = "token",
                    Value = token,
                    Expires = DateTime.Now.AddDays(10)
                });
                var cookieManager = CefSharp.Cef.GetGlobalCookieManager();
                cookieManager.SetCookie(url, new Cookie()
                {
                    Domain = AppStatic.Server,
                    Name = "token",
                    Value = token,
                    Expires=DateTime.Now.AddDays(10)
                });
                if (obj.ContainsKey("needBinding"))
                {
                    string isBinding = obj.Value<string>("needBinding");
                    AppStatic.needRegister = isBinding == "1" ? true : false;
                    return true;
                } 
                else if(status==401)
                {
                    MessageBox.Show(obj.Value<string>("msg"));
                    return false;
                }
                else
                {
                    return true;
                }
            }
            else
            {
                MessageBox.Show(obj.Value<string>("msg"));
                return false;
            }
        }
        else
        {
            MessageBox.Show("程序异常，请联系管理员");
        }
        return false;
    }

    public bool requestAuthorize(string mac)
    {
        var request = new RestRequest("/sys/authorize", Method.POST, RestSharp.DataFormat.Json);
        var contenType = "application/json";
        request.AddHeader("Accept", contenType);
        var logininfo = new AuthorizeInfo()
        {
            mac = mac
        };
        string jsonStr = JsonConvert.SerializeObject(logininfo);
        request.AddParameter(contenType, jsonStr, ParameterType.RequestBody);
        var response = client.Execute(request);
        if (response.StatusCode == System.Net.HttpStatusCode.OK)
        {
            JObject obj = (JObject)JsonConvert.DeserializeObject(response.Content);
            int status = obj.Value<int>("code");
            if (status == 0)
            {
                return true;
            }
            else
            {
                MessageBox.Show(obj.Value<string>("msg"));
                return false;
            }
        }
        else
        {
            MessageBox.Show("程序异常，请联系管理员");
        }
        return false;
    }
    

    public string uuid()
    {
        return System.Guid.NewGuid().ToString();
    }


    private RSACryptoServiceProvider CreateRsaProviderFromPublicKey(string publicKeyString)
    {
        // encoded OID sequence for  PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
        byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
        byte[] x509key;
        byte[] seq = new byte[15];
        int x509size;
 
        x509key = Convert.FromBase64String(publicKeyString);
        x509size = x509key.Length;
 
        // ---------  Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob  ------
        using (MemoryStream mem = new MemoryStream(x509key))
        {
            using (BinaryReader binr = new BinaryReader(mem))  //wrap Memory Stream with BinaryReader for easy reading
            {
                byte bt = 0;
                ushort twobytes = 0;
 
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                    binr.ReadByte();    //advance 1 byte
                else if (twobytes == 0x8230)
                    binr.ReadInt16();   //advance 2 bytes
                else
                    return null;
 
                seq = binr.ReadBytes(15);       //read the Sequence OID
                if (!CompareBytearrays(seq, SeqOID))    //make sure Sequence for OID is correct
                    return null;
 
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81)
                    binr.ReadByte();    //advance 1 byte
                else if (twobytes == 0x8203)
                    binr.ReadInt16();   //advance 2 bytes
                else
                    return null;
 
                bt = binr.ReadByte();
                if (bt != 0x00)     //expect null byte next
                    return null;
 
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                    binr.ReadByte();    //advance 1 byte
                else if (twobytes == 0x8230)
                    binr.ReadInt16();   //advance 2 bytes
                else
                    return null;
 
                twobytes = binr.ReadUInt16();
                byte lowbyte = 0x00;
                byte highbyte = 0x00;
 
                if (twobytes == 0x8102) //data read as little endian order (actual data order for Integer is 02 81)
                    lowbyte = binr.ReadByte();  // read next bytes which is bytes in modulus
                else if (twobytes == 0x8202)
                {
                    highbyte = binr.ReadByte(); //advance 2 bytes
                    lowbyte = binr.ReadByte();
                }
                else
                    return null;
                byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };   //reverse byte order since asn.1 key uses big endian order
                int modsize = BitConverter.ToInt32(modint, 0);
 
                int firstbyte = binr.PeekChar();
                if (firstbyte == 0x00)
                {   //if first byte (highest order) of modulus is zero, don't include it
                    binr.ReadByte();    //skip this null byte
                    modsize -= 1;   //reduce modulus buffer size by 1
                }
 
                byte[] modulus = binr.ReadBytes(modsize);   //read the modulus bytes
 
                if (binr.ReadByte() != 0x02)            //expect an Integer for the exponent data
                    return null;
                int expbytes = (int)binr.ReadByte();        // should only need one byte for actual exponent data (for all useful values)
                byte[] exponent = binr.ReadBytes(expbytes);
 
                // ------- create RSACryptoServiceProvider instance and initialize with public key -----
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                RSAParameters RSAKeyInfo = new RSAParameters();
                RSAKeyInfo.Modulus = modulus;
                RSAKeyInfo.Exponent = exponent;
                RSA.ImportParameters(RSAKeyInfo);
 
                return RSA;
            }
 
        }
    }
    private bool CompareBytearrays(byte[] a, byte[] b)
    {
        if (a.Length != b.Length)
            return false;
        int i = 0;
        foreach (byte c in a)
        {
            if (c != b[i])
                return false;
            i++;
        }
        return true;
    }

    public void downExcel(string[] ids,string fileName)
    {
        var request = new RestRequest("/export/index", Method.POST, RestSharp.DataFormat.Json);
        var contenType = "application/json";
        request.AddHeader("Accept", contenType);
        var logininfo = new exportdata()
        {
            indexes = ids
        };
        string jsonStr = JsonConvert.SerializeObject(logininfo);
        //string enryData = Convert.ToBase64String(rsa.Encrypt(Encoding.UTF8.GetBytes(jsonStr), false));
        //JObject sendData = new JObject();
        //sendData.Add("data", jsonStr);
        request.AddParameter(contenType, jsonStr, ParameterType.RequestBody);
        try
        {
            using (var writer = File.OpenWrite(fileName))
            {
                request.ResponseWriter = responseStream =>
                {
                    using (responseStream)
                    {
                        responseStream.CopyTo(writer);
                    }
                };
                var response = client.DownloadData(request);
            }
            MessageBox.Show("文件下载完成");
        }
        catch (Exception ex)
        {
            MessageBox.Show("网络异常");
        }
    }
}

public class loginInfo
{
    public string username;
    public string password;
    public string mac;
}

public class AuthorizeInfo
{
    public string mac;
}

public class exportdata
{
    public string[] indexes;
}